#include "Server.h"

using boost::asio::ip::udp;

/*Shared variables and mutex*/
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
std::string msg;

Server::Server(boost::asio::io_service& io_service)
    : socket_(io_service, udp::endpoint(udp::v4(), 13)){

    start_receive();

}

Server::~Server(){

}


void Server::start_receive()
  {
    socket_.async_receive_from(boost::asio::buffer(recv_buffer_), remote_endpoint_,
        boost::bind(&Server::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
  }

void Server::handle_receive(const boost::system::error_code& error,
      std::size_t)
  {
    if (!error || error == boost::asio::error::message_size)
    {
      boost::shared_ptr<std::string> message(new std::string(msg));

      socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
          boost::bind(&Server::handle_send, this, message,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));

      start_receive();
    }
  }

void Server::handle_send(boost::shared_ptr<std::string>,
      const boost::system::error_code&,
      std::size_t){
}


void *sendMsg(void*ptr){
  try
  {
    boost::asio::io_service io_service;
    Server server(io_service);
    io_service.run();

  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }
}

void *graphics(void*ptr){
    KinectInterface kinect;

    kinect.graphics(msg);
}

int main(int argc, char **argv) {

    msg = "hej\n";
    pthread_t graphicsThread, serverThread;
    char *message1 = "";
    char *message2 = "";
    int  iret1, iret2;

    //Create threads
    iret1 = pthread_create( &graphicsThread, NULL, graphics, (void*) message1);
    iret2 = pthread_create( &serverThread, NULL, sendMsg, (void*) message2);

    //Join threads
    pthread_join( graphicsThread, NULL);
    pthread_join( serverThread, NULL);

	return 0;
}





